package com.master.demo.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.master.common.api.IPageInfo;
import com.master.common.api.Query;
import com.master.common.api.ResponseInfo;
import com.master.common.exception.ErrorException;
import com.master.common.utils.DateUtil;
import com.master.common.utils.DozerUtil;
import com.master.common.validator.ValidatorUtil;
import com.master.demo.sys.mapper.AppConfigMapper;
import com.master.demo.sys.pojo.command.AppConfigCommand;
import com.master.demo.sys.pojo.entity.AppConfig;
import com.master.demo.sys.pojo.vo.AppConfigVO;
import com.master.demo.sys.service.IAppConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 基础配置 服务实现类
 *
 * @author: Yang
 * @date: 2023-04-28
 * @version: 1.0.0
 * Copyright Ⓒ 2022 Master Computer Corporation Limited All rights reserved.
 */
@Slf4j
@Service
public class AppConfigServiceImpl extends ServiceImpl<AppConfigMapper, AppConfig> implements IAppConfigService {
    @Autowired
    private AppConfigMapper appConfigMapper;

    /**
     * 根据id获取基础配置信息
     *
     * @param id 基础配置id
     * @return
     */
    private AppConfig getAppConfig(Long id) {
        AppConfig appConfig = appConfigMapper.selectById(id);
        if (ValidatorUtil.isNull(appConfig)) {
            throw new ErrorException("基础配置信息不存在，无法操作");
        }
        return appConfig;
    }

    @Override
    public ResponseInfo<IPageInfo<AppConfigVO>> pageAppConfig(Query query) {
        IPage<AppConfigVO> iPage = appConfigMapper.pageAppConfig(new Page<>(query.getCurrent(), query.getSize()), query);
        return ResponseInfo.success(new IPageInfo(iPage.getCurrent(), iPage.getSize(), iPage.getTotal(), iPage.getRecords()));
    }

    @Override
    public ResponseInfo<List<AppConfigVO>> listAppConfig(Query query) {
        return ResponseInfo.success(appConfigMapper.listAppConfig(query));
    }

    @Override
    public ResponseInfo<AppConfigVO> getAppConfigById(Long id) {
        return ResponseInfo.success(DozerUtil.convertor(getAppConfig(id), AppConfigVO.class));
    }

    @Override
    public <T> T getAppConfigByName(String name, Class<T> t) {
        AppConfig appConfig = appConfigMapper.selectOne(new LambdaQueryWrapper<AppConfig>().eq(AppConfig::getName, name));
        if (ValidatorUtil.isNull(appConfig) || ValidatorUtil.isNull(appConfig.getData())) {
            return null;
        }
        return JSON.parseObject(appConfig.getData(), t);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "masterTransactionManager")
    public ResponseInfo test(String name) {
        log.info("开始打印：{}，时间：{}", Thread.currentThread().getName(), DateUtil.getCurrentTime());
        AppConfig appConfig = AppConfig.builder().name("测试").build();
        appConfig.setName("测试dw");
        appConfigMapper.insert(appConfig);
        try {
            log.info("进入休眠：{}，时间：{}", Thread.currentThread().getName(), DateUtil.getCurrentTime());
            Thread.sleep(10000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        appConfig = appConfigMapper.selectById(appConfig.getId());
        log.info("查询结果：{}，时间：{}", appConfig.getName(), DateUtil.getCurrentTime());
        log.info("结束打印：{}，时间：{}", Thread.currentThread().getName(), DateUtil.getCurrentTime());
        return ResponseInfo.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "masterTransactionManager")
    public ResponseInfo saveAppConfig(AppConfigCommand command) {
        AppConfig appConfig = appConfigMapper.selectOne(new LambdaQueryWrapper<AppConfig>().eq(AppConfig::getName, command.getName()));
        if (ValidatorUtil.isNotNull(appConfig)) {
            return updateAppConfig(command);
        }
        appConfig = DozerUtil.convertor(command, AppConfig.class);
        appConfig.setCreateUser(command.getOperater());
        appConfigMapper.insert(appConfig);
        return ResponseInfo.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "masterTransactionManager")
    public ResponseInfo updateAppConfig(AppConfigCommand command) {
        AppConfig appConfig = appConfigMapper.selectOne(new LambdaQueryWrapper<AppConfig>().eq(AppConfig::getName, command.getName()));
        appConfig.setUpdateUser(command.getOperater());
        appConfig.setUpdateTime(LocalDateTime.now());
        appConfig.setData(command.getData());
        appConfigMapper.updateById(appConfig);
        return ResponseInfo.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "masterTransactionManager")
    public ResponseInfo removeAppConfigByIds(List<Long> ids) {
        appConfigMapper.deleteBatchIds(ids);
        return ResponseInfo.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "masterTransactionManager")
    public ResponseInfo removeAppConfigById(Long id) {
        appConfigMapper.deleteById(id);
        return ResponseInfo.success();
    }

}
